{% extends 'layout.html' %}

{% block content %}
    <div class="container">
        <div>
            <!-- Button trigger modal -->
            <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal">
                新建订单1
            </button>
            <!-- JS实现除法 -->
            <input id="btnAdd" type="button" value="新建订单2" class="btn btn-primary">
        </div>
        <div class="panel panel-default">
            <div class="panel-heading">
                订单列表
            </div>
            <table class="table table-bordered">
                <thead>
                <tr>
                    <th>ID</th>
                    <th>订单号</th>
                    <th>商品名称</th>
                    <th>价格</th>
                    <th>状态</th>
                    <th>用户ID</th>
                    <th>操作</th>
                </tr>
                </thead>
                <tbody>
                {% for obj in queryset %}
                    <tr uid="{{ obj.id }}">
                        <th scope="row">{{ obj.id }}</th>
                        <td>{{ obj.oid }}</td>
                        <td>{{ obj.title }}</td>
                        <td>{{ obj.price }}</td>
                        <td>{{ obj.get_status_display }}</td>
                        <td>{{ obj.admin.username }}</td>

                        <td>
                            <input uid="{{ obj.id }}" type="button" class="btn btn-primary btn-xs btn-edit" value="编辑">
                            <a class="btn btn-danger btn-xs" href="/order/{{ obj.id }}/delete/">删除1</a>
                            <input uid="{{ obj.id }}" type="button" class="btn btn-danger btn-xs btn-delete"
                                   value="删除2">
                        </td>
                    </tr>
                {% endfor %}

                </tbody>

            </table>


        </div>
        <ul class="pagination">
            {{ page_string }}
        </ul>
    </div>




    <!-- 弹出输入框 myModal -->
    <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                            aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title" id="myModalLabel">新建订单</h4>
                </div>
                <div class="modal-body">

                    <div class="panel panel-default">
                        <div class="panel-heading">订单信息</div>
                        <div class="panel-body">
                            <form id="formAdd">
                                {# {% csrf_token %} #}
                                <div class="clearfix">
                                    {% for field in form %}
                                        <div class="col-xs-12">
                                            <div class="form-group" style="position: relative;margin-bottom: 20px">
                                                <label>{{ field.label }}</label>
                                                {{ field }}
                                                <span class="error-msg" style="color: red; position: absolute"></span>
                                            </div>
                                        </div>
                                    {% endfor %}
                                </div>
                            </form>
                        </div>
                    </div>

                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                    <button id="btnSave" type="button" class="btn btn-primary">保存</button>
                </div>
            </div>
        </div>
    </div>

    <!--弹出警告框  myModal -->
    <div class="modal fade" id="deleteModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="alert alert-danger alert-dismissible fade in" role="alert">
                    {#                    <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span#}
                    {#                            aria-hidden="true">×</span></button>#}
                    <h4>确认删除该订单?</h4>
                    <p style="margin: 20px 0"> 订单id编号：{{ DELETE_ID }}</p>
                    <p style="text-align: right">
                        <button style="margin: 20px" type="button" class="btn btn-default" data-dismiss="modal">取 消
                        </button>
                        <button id="btnConfirmDelete" type="button" class="btn btn-danger">确 定</button>
                    </p>
                </div>
            </div>
        </div>
    </div>



{% endblock %}

{% block js %}
    <script type="text/javascript">
        var DELETE_ID;// 全局变量记录删除ID
        var EDIT_ID;

        $(function () {
            bindBtnAddEvent();
            bindBtnSaveEvent();
            bindBtnDeleteEvent();
            bindBtnConfirmDeleteEvent();
            bindBtnEditEvent();
        })

        function bindBtnAddEvent() {
            $("#btnAdd").click(function () {
                EDIT_ID = undefined// 将正在编辑的id置空

                $("#formAdd")[0].reset();// 清空原来的弹出框数据
                $('#myModalLabel').text("新建");
                $('#myModal').modal('show');

            });
        }

        function bindBtnSaveEvent() {
            $("#btnSave").click(function () {

                $(".error_msg").empty()

                if (EDIT_ID) {
                    doEdit();
                } else {
                    doAdd();
                }
                // 添加请求

            });
        }

        function doAdd() {
            $.ajax({
                url: '/order/add/',
                type: "post",
                data: $("#formAdd").serialize(),
                dataType: "JSON",
                success: function (res) {
                    if (res.status) {
                        //alert("添加成功");
                        location.reload();// 整个网页刷新
                        //$('#formAdd')[0].reset();// 表单清空，$('#formAdd')是jQuery对象，$('#formAdd')[0]是DOM对象
                        $('#myModal').modal('hide');
                    } else {
                        console.log(res.error);// 是res.error,不是res.error()
                        $.each(res.error, function (name, data) {// 是res.error,不是res.error()
                            //console.log(name,data);
                            $("#id_" + name).next().text(data[0]);
                        })
                    }
                }
            })
        }

        function doEdit() {
            $.ajax({
                url: "/order/edit/" + "?uid=" + EDIT_ID,   //  /order/edit/?uid=123
                type: "post",
                data: $("#formAdd").serialize(),
                dataType: "JSON",
                success: function (res) {
                    if (res.status) {

                        location.reload();// 整个网页刷新
                        //$('#formAdd')[0].reset();// 表单清空，$('#formAdd')是jQuery对象，$('#formAdd')[0]是DOM对象
                        //$('#myModal').modal('hide');
                    } else {
                        if (res.tips) {
                            alert(res.tips);
                        } else {
                            console.log(res.error);// 是res.error,不是res.error()
                            $.each(res.error, function (name, data) {// 是res.error,不是res.error()
                                //console.log(name,data);
                                $("#id_" + name).next().text(data[0]);
                            })
                        }

                    }
                }
            })
        }

        function bindBtnDeleteEvent() {
            // 不绑定id="#btnDetlete"，id会重复，导致只用第一个id="#btnDetlete"有效
            // 绑定class".btn-delete" 添加了这个样式的都能响应
            $(".btn-delete").click(function () {
                // 获取当前行的ID并赋值给全局变量。
                DELETE_ID = $(this).attr("uid");
                //console.log(DELETE_ID);
                $('#deleteModal').modal('show');

            });
        }

        function bindBtnConfirmDeleteEvent() {
            $("#btnConfirmDelete").click(function () {
                $.ajax({
                    //url: "/order/"+DELETE_ID+"/delete/",   =>/order/delete/?uid=123
                    url: "/order/delete/",  //
                    type: "GET",
                    data: {
                        uid: DELETE_ID
                    },
                    dataType: "JSON",
                    success: function (res) {
                        if (res.status) {
                            alert("删除成功");
                            $('#deleteModal').modal('hide');


                            // 刷新页面方法
                            // 方法1. location.reload(); 后端reload,服务器压力大
                            // 方法2. 前端删除行 <tr uid={{ obj.id }}></tr>，分页不会更新
                            $("tr[uid='" + DELETE_ID + "']").remove();

                            DELETE_ID = 0;
                        } else {
                            console.log(res.error);
                            alert(res.error);
                            $('#deleteModal').modal('hide');
                            location.reload();
                        }
                    }
                })
            });
        }

        function bindBtnEditEvent() {
            $(".btn-edit").click(function () {
                var uid = $(this).attr("uid");
                EDIT_ID = uid;

                // 发送Ajax去后端获取当前行的相关数据
                $.ajax({
                    url: "/order/detail/",
                    type: "GET",
                    data: {
                        uid: uid
                    },
                    dataType: "JSON",
                    success: function (res) {
                        if (res.status) {
                            $("#formAdd")[0].reset();// 清空原来的弹出框数据
                            $("#myModalLabel").text("编辑");
                            $("#myModal").modal('show');
                            console.log(res)
                            $.each(res.data, function (name, value) {
                                $("#id_" + name).val(value);
                            })
                        } else {
                            alert(res.error)
                            $('#myModal').modal('hide');
                            location.reload();
                        }
                    },
                })
            });
        }

    </script>
{% endblock %}